<?php
class TurntableService {
    /**
     * @var TurntableService
     */
    private static $instance;

    /**
     * Get the instance of TurntableService.
     *
     * @return TurntableService
     */
    public static function get() {
        if (!self::$instance) {
            self::$instance = new TurntableService();
        }
        return self::$instance;
    }

    /**
     * Construction.
     */
    protected function __construct() {

    }

    public function play($userId) {
        $turntableSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_TURNTABLE, null, true);
        if (!$turntableSetting) {
            return; // 配置不存在
        }

        // 扣除道具
        GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_CONSUME_TURNTABLE_COIN, 1, true);
        $input = GameConst::ENTITY_ACTION_CONSUME_TURNTABLE_COIN.':1|';
        $total = 0;
        // 获取道具
        foreach ($turntableSetting as &$turntable) {
            $total += $turntable['weight'];
            $turntable['rate'] = $total;
        }

        $num = mt_rand(1,$total);
        foreach ($turntableSetting as $v) {
            if ($v['rate'] >= $num) {
                $reward = $v;
                break;
            }
        }

        if (!$reward) {
            return;
        }
        $output = '';
        // 添加道具
        foreach ($reward['award'] as $entityId=>$count) {
            $output .= $entityId.':'.$count.'|';
            GameService::get()->handleEntity($userId, $entityId, $count, true, true);
        }

        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:lottery|action:start|',
                'item' => 1,
                'value' => 1
            )
        ));

        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_INPUT, array(
            'clientData' => array(
                'tid' => $input,
                'item' => 'lottery_start'
            )
        ));

        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => $output,
                'item' => 'lottery_start'
            )
        ));

        return $reward;
    }
}